import 'package:flutter/material.dart';
import '../constants/app_colors.dart';
import '../constants/language_list.dart';

class LanguageSelector extends StatelessWidget {
  final String sourceLanguage;
  final String targetLanguage;
  final VoidCallback onSwap;
  final Function(String) onSourceLanguageChanged;
  final Function(String) onTargetLanguageChanged;
  final bool isCompact; // 是否使用紧凑模式（适用于顶部栏）

  const LanguageSelector({
    Key? key,
    required this.sourceLanguage,
    required this.targetLanguage,
    required this.onSwap,
    required this.onSourceLanguageChanged,
    required this.onTargetLanguageChanged,
    this.isCompact = false,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    if (isCompact) {
      // 紧凑模式，适用于顶部栏
      return Container(
        padding: const EdgeInsets.symmetric(vertical: 6, horizontal: 12),
        decoration: BoxDecoration(
          color: AppColors.cardBackground,
          border: Border.all(color: AppColors.primary.withValues(alpha: 0.2), width: 1),
          borderRadius: BorderRadius.circular(16),
        ),
        child: Row(
          mainAxisSize: MainAxisSize.min,
          children: [
            _buildLanguageButton(
              context,
              sourceLanguage,
              onSourceLanguageChanged,
              true
            ),
            GestureDetector(
              onTap: onSwap,
              child: Container(
                padding: const EdgeInsets.symmetric(horizontal: 6),
                child: const Icon(
                  Icons.swap_horiz_rounded,
                  color: AppColors.primary,
                  size: 18,
                ),
              ),
            ),
            _buildLanguageButton(
              context,
              targetLanguage,
              onTargetLanguageChanged,
              false
            ),
          ],
        ),
      );
    } else {
      // 常规模式，适用于翻译页面
      return Container(
        padding: const EdgeInsets.symmetric(vertical: 8, horizontal: 16),
        decoration: BoxDecoration(
          color: AppColors.cardBackground,
          borderRadius: BorderRadius.circular(16),
        ),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            _buildLanguageButton(
              context,
              sourceLanguage,
              onSourceLanguageChanged,
              true
            ),
            GestureDetector(
              onTap: onSwap,
              child: Container(
                padding: const EdgeInsets.all(10),
                decoration: const BoxDecoration(
                  color: AppColors.buttonSwap,
                  shape: BoxShape.circle,
                ),
                child: const Icon(
                  Icons.swap_horiz,
                  color: AppColors.iconSwap,
                  size: 24,
                ),
              ),
            ),
            _buildLanguageButton(
              context,
              targetLanguage,
              onTargetLanguageChanged,
              false
            ),
          ],
        ),
      );
    }
  }

  // 构建语言选择按钮
  Widget _buildLanguageButton(
    BuildContext context,
    String currentValue,
    Function(String) onChanged,
    bool isSource
  ) {
    return GestureDetector(
      onTap: () {
        _showLanguageSelectionDialog(context, currentValue, onChanged, isSource);
      },
      child: Row(
        mainAxisSize: isCompact ? MainAxisSize.min : MainAxisSize.max,
        children: [
          Text(
            _getDisplayLanguage(currentValue),
            style: const TextStyle(
              color: AppColors.textPrimary,
              fontSize: 14,
              fontWeight: FontWeight.w500
            ),
          ),
          Icon(
            Icons.keyboard_arrow_down_rounded,
            color: AppColors.textPrimary,
            size: isCompact ? 18 : 18
          ),
        ],
      ),
    );
  }

  // 显示语言选择对话框
  void _showLanguageSelectionDialog(
    BuildContext context,
    String currentLanguage,
    Function(String) onChanged,
    bool isSource
  ) {
    showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      backgroundColor: Colors.transparent,
      builder: (context) => _LanguageSelectionDialog(
        currentLanguage: currentLanguage,
        onLanguageSelected: (language) {
          onChanged(language);
          Navigator.pop(context);
        },
        isSource: isSource,
      ),
    );
  }

  // 获取语言显示名称
  String _getDisplayLanguage(String languageCode) {
    // 获取支持的语言列表
    final supportedLanguages = LanguageCodes.getSupportedLanguages();
    
    // 查找匹配的语言
    for (var language in supportedLanguages) {
      if (language['code'] == languageCode) {
        String displayName = language['name']!;
        
        // 移除国家信息，只保留语言名称
        if (displayName.contains('(')) {
          displayName = displayName.substring(0, displayName.indexOf('(')).trim();
        }
        
        return displayName;
      }
    }

    // 如果没找到匹配的语言代码，返回原代码
    return languageCode;
  }
}

// 语言选择对话框
class _LanguageSelectionDialog extends StatefulWidget {
  final String currentLanguage;
  final Function(String) onLanguageSelected;
  final bool isSource;

  const _LanguageSelectionDialog({
    Key? key,
    required this.currentLanguage,
    required this.onLanguageSelected,
    required this.isSource,
  }) : super(key: key);

  @override
  State<_LanguageSelectionDialog> createState() => _LanguageSelectionDialogState();
}

class _LanguageSelectionDialogState extends State<_LanguageSelectionDialog> {
  late TextEditingController _searchController;
  List<Map<String, String>> _filteredLanguages = [];
  List<Map<String, String>> _allLanguages = [];

  @override
  void initState() {
    super.initState();
    _searchController = TextEditingController();
    _allLanguages = LanguageCodes.getSupportedLanguages();
    _filteredLanguages = List.from(_allLanguages);
  }

  @override
  void dispose() {
    _searchController.dispose();
    super.dispose();
  }

  // 搜索语言
  void _filterLanguages(String query) {
    setState(() {
      if (query.isEmpty) {
        _filteredLanguages = List.from(_allLanguages);
      } else {
        final lowerQuery = query.toLowerCase();
        _filteredLanguages = _allLanguages
            .where((language) =>
                language['code']!.toLowerCase().contains(lowerQuery) ||
                language['name']!.toLowerCase().contains(lowerQuery) ||
                language['nativeName']!.toLowerCase().contains(lowerQuery))
            .toList();
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      height: MediaQuery.of(context).size.height * 0.9,
      decoration: const BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.only(
          topLeft: Radius.circular(5),
          topRight: Radius.circular(5),
        ),
      ),
      child: Column(
        children: [
          // 标题栏
          Padding(
            padding: const EdgeInsets.fromLTRB(20, 16, 20, 0),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                const Text(
                  '选择语言',
                  style: TextStyle(
                    fontSize: 18,
                    fontWeight: FontWeight.bold,
                    color: Colors.black,
                  ),
                ),
                IconButton(
                  icon: const Icon(Icons.close),
                  onPressed: () => Navigator.pop(context),
                ),
              ],
            ),
          ),

          // 搜索框
          Padding(
            padding: const EdgeInsets.all(16.0),
            child: TextField(
              controller: _searchController,
              onChanged: _filterLanguages,
              decoration: InputDecoration(
                hintText: '搜索语言...',
                prefixIcon: const Icon(Icons.search, color: Colors.grey),
                border: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(10),
                  borderSide: BorderSide.none,
                ),
                filled: true,
                fillColor: Colors.grey[100],
                contentPadding: const EdgeInsets.symmetric(vertical: 0),
              ),
            ),
          ),

          // 语言列表
          Expanded(
            child: ListView.builder(
              itemCount: _filteredLanguages.length,
              itemBuilder: (context, index) {
                final language = _filteredLanguages[index];
                final isSelected = widget.currentLanguage == language['code'] ||
                                   widget.currentLanguage == _getShortLanguageName(language['name']!);

                return Column(
                  children: [
                    ListTile(
                      title: Text(
                        language['name']!,
                        style: TextStyle(
                          color: isSelected ? AppColors.primary : Colors.black,
                          fontWeight: isSelected ? FontWeight.bold : FontWeight.normal,
                        ),
                      ),
                      subtitle: Text(
                        language['nativeName']!,
                        style: TextStyle(
                          color: Colors.grey[600],
                          fontSize: 12,
                        ),
                      ),
                      trailing: isSelected
                          ? const Icon(Icons.check_circle, color: AppColors.primary)
                          : null,
                      onTap: () {
                        // 选择后使用code作为语言标识
                        widget.onLanguageSelected(language['code']!);
                      },
                    ),
                    const Divider(height: 1),
                  ],
                );
              },
            ),
          ),
        ],
      ),
    );
  }

  // 获取简短的语言名称（去掉国家信息）
  String _getShortLanguageName(String fullName) {
    if (fullName.contains(' (')) {
      return fullName.substring(0, fullName.indexOf(' ('));
    }
    return fullName;
  }
}